/*
 * Copyright© 2003-2019 浙江汇信科技有限公司, All Rights Reserved.
 */
package com.icinfo.cloud.provider.punish.config.service.impl;

import cn.hutool.core.util.ObjectUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.icinfo.cloud.common.security.util.UserUtil;
import com.icinfo.cloud.provider.common.constant.Constant;
import com.icinfo.cloud.provider.common.enums.RecordSaveTypeEnum;
import com.icinfo.cloud.provider.common.enums.YesOrNoEnum;
import com.icinfo.cloud.provider.common.exception.BusinessException;
import com.icinfo.cloud.provider.common.utils.BaseUtil;
import com.icinfo.cloud.provider.peripheralinterface.xzzf.service.IXzzfInterfaceService;
import com.icinfo.cloud.provider.punish.api.dto.DeptInfoSyncDto;
import com.icinfo.cloud.provider.punish.approval.vo.CaseApprovalCenterInfoVo;
import com.icinfo.cloud.provider.punish.approval.vo.LineTerritoryInfoVo;
import com.icinfo.cloud.provider.punish.common.seal.model.ConfigOrgRelatedSeal;
import com.icinfo.cloud.provider.punish.common.seal.vo.ConfigOrgRelatedSealVo;
import com.icinfo.cloud.provider.punish.config.dto.ConfigDeptParamDto;
import com.icinfo.cloud.provider.punish.config.dto.ConfigDeptParamRequest;
import com.icinfo.cloud.provider.punish.config.dto.ConfigDeptSpecialParamDto;
import com.icinfo.cloud.provider.punish.config.dto.ConfigOrgDecideBasisInfoQueryDto;
import com.icinfo.cloud.provider.punish.config.enums.AdjustDeptInfoTypeEnum;
import com.icinfo.cloud.provider.punish.config.enums.DecideBasisTypeEnum;
import com.icinfo.cloud.provider.punish.config.mapper.ConfigOrgRelatedSealMapper;
import com.icinfo.cloud.provider.punish.config.mapper.ConfigPaymentChannelInfoMapper;
import com.icinfo.cloud.provider.punish.config.mapper.SysDepartParamMapper;
import com.icinfo.cloud.provider.punish.config.model.ConfigOrgDecideBasisInfo;
import com.icinfo.cloud.provider.punish.config.model.ConfigPaymentChannelInfo;
import com.icinfo.cloud.provider.punish.config.model.SysDepartParam;
import com.icinfo.cloud.provider.punish.config.service.IConfigOrgDecideBasisInfoService;
import com.icinfo.cloud.provider.punish.config.service.IConfigOrgRelatedSealService;
import com.icinfo.cloud.provider.punish.config.service.IConfigPaymentChannelInfoService;
import com.icinfo.cloud.provider.punish.config.service.ISysDepartParamService;
import com.icinfo.cloud.provider.punish.config.vo.ConfigDeptParamKeyInfoVo;
import com.icinfo.cloud.provider.punish.config.vo.ConfigDeptParamVo;
import com.icinfo.cloud.provider.punish.config.vo.ConfigPaymentChannelInfoVo;
import com.icinfo.cloud.provider.punish.config.vo.LineCaseHandleInfoVo;
import com.icinfo.cloud.provider.punish.evideinv.service.EvidenceInventoryService;
import com.icinfo.cloud.provider.punish.ucase.caseadditional.dto.CaseAdditionalRecordDto;
import com.icinfo.cloud.xzcf.provider.member.line.dto.LineDTO;
import com.icinfo.cloud.xzcf.provider.member.userinfo.dto.UserDTO;
import com.icinfo.framework.common.web.Result;
import com.icinfo.framework.core.service.support.MyBatisServiceSupport;
import com.icinfo.framework.mybatis.mapper.entity.Example;
import com.icinfo.framework.tools.utils.StringUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.ObjectUtils;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 描述: 部门参数 sys_depart_param 对应的Service接口实现类.<br>
 *
 * @author framework generator
 * @date 2022年03月24日
 */
@Service
@Slf4j
public class SysDepartParamServiceImpl extends MyBatisServiceSupport implements ISysDepartParamService {

    @Resource
    private SysDepartParamMapper sysDepartParamMapper;
    @Resource
    private ConfigPaymentChannelInfoMapper configPaymentChannelInfoMapper;
    @Resource
    private ConfigOrgRelatedSealMapper configOrgRelatedSealMapper;
    @Resource
    private IConfigOrgRelatedSealService configOrgRelatedSealService;
    @Resource
    private IConfigPaymentChannelInfoService configPaymentChannelInfoService;
    @Resource
    private IXzzfInterfaceService xzzfInterfaceService;
    @Resource
    private IConfigOrgDecideBasisInfoService configOrgDecideBasisInfoService;
    @Resource
    private EvidenceInventoryService evidenceInventoryService;
    /**
     * 根据机构编码获取部门配置信息
     *
     * @param orgCode
     * @param deptCode
     * @return {@link SysDepartParam}
     * @author liyafeng
     * @date 2022/3/31
     */
    @Override
    public SysDepartParam getSysDepartParamByOrgCode(String orgCode,String deptCode) {
        /*if (StringUtils.isNotEmpty(handleDeptCode)) {
            Example queryExample = new Example(SysDepartParam.class);
            queryExample.createCriteria().andEqualTo("orgCode", handleDeptCode);
            //不确定要不要改 todo
            List<SysDepartParam> sysDepartParamList = sysDepartParamMapper.selectByExample(queryExample);
            if (sysDepartParamList.size() > 0) {
                return sysDepartParamList.get(0);
            } else {
                throw new BusinessException("部门参数配置信息为空！");
            }
        } else {
            throw new BusinessException("非法传值，部门编码deptCode为空！");
        }*/
        return getSysDepartParamByOrgCodeAndDeptCode(orgCode,deptCode);
    }


    /**
     * 【V2.0.0】描述：查询已配置的部门信息列表
     *
     * @return {@link List<ConfigDeptParamKeyInfoVo>} 已配置的部门关键信息列表
     * @author xiangyuyu
     * @date 2022-05-16 16:16
     */
    @Override
    public List<ConfigDeptParamKeyInfoVo> getExistsDeptKeyInfoList() {
        List<ConfigDeptParamKeyInfoVo> list = new ArrayList<>();
        //TODO:业务待完善
        return list;
    }


    /**
     * 【V1.3.1】描述：根据指定条件查询部门参数配置信息
     *
     * @param request {@link ConfigDeptParamRequest}
     * @return {@link Result<ConfigDeptParamVo>} 部门参数配置信息
     * @author xiangyuyu
     * @date 2022-05-16 16:16
     */
    @Override
    public ConfigDeptParamVo getDeptConfigInfoWithSpecialCondition(ConfigDeptParamRequest request) {
        String uniscid = request.getUniscid();
        String orgCode = request.getOrgCode();
        String deptCode=request.getDeptCode();
        String id = request.getId();
        String isConfigDept=Constant.STRING_0;
        if (ObjectUtils.isEmpty(uniscid) && ObjectUtils.isEmpty(orgCode) && ObjectUtils.isEmpty(id)) {
            throw new BusinessException("请指定统一社会信用代码或机构编码或主键id");
        }
        List<SysDepartParam> sysDepartParamList=new ArrayList<>();
        StringBuilder logInfo = new StringBuilder();
        //获取机构基本信息
        Example query = new Example(SysDepartParam.class);
        Example.Criteria criteria = query.createCriteria();
        if (!ObjectUtils.isEmpty(id)) {
            criteria.andEqualTo("id", id);
            logInfo.append("id:" + id + " ");
        }
        if (!ObjectUtils.isEmpty(uniscid)) {
            criteria.andEqualTo("unicode", uniscid);
            logInfo.append("uniscid:" + uniscid + " ");
        }
        if (!ObjectUtils.isEmpty(orgCode)) {
            criteria.andEqualTo("orgCode", orgCode);
            logInfo.append("orgCode:" + orgCode + " ");
        }
        criteria.andCondition("(dept_code is null or dept_code='') ").andEqualTo("isDeleted",Constant.STRING_0);
        List<SysDepartParam> sysDepartParamOrgList = sysDepartParamMapper.selectByExample(query);
        if (!ObjectUtils.isEmpty(sysDepartParamOrgList)) {
            sysDepartParamList = sysDepartParamOrgList;
            if(StringUtils.isNotBlank(deptCode)) {
                Example queryDept = new Example(SysDepartParam.class);
                Example.Criteria criteriaDept = queryDept.createCriteria();
                if (!ObjectUtils.isEmpty(id)) {
                    criteriaDept.andEqualTo("id", id);
                    logInfo.append("id:" + id + " ");
                }
                if (!ObjectUtils.isEmpty(uniscid)) {
                    criteriaDept.andEqualTo("unicode", uniscid);
                    logInfo.append("uniscid:" + uniscid + " ");
                }
                if (!ObjectUtils.isEmpty(orgCode)) {
                    criteriaDept.andEqualTo("orgCode", orgCode);
                    logInfo.append("orgCode:" + orgCode + " ");
                }
                if (!ObjectUtils.isEmpty(deptCode)) {
                    criteriaDept.andEqualTo("deptCode", deptCode);
                    logInfo.append("deptCode:" + deptCode + " ");
                }
                criteriaDept.andEqualTo("isDeleted", Constant.STRING_0);
                List<SysDepartParam> sysDepartParamDeptList = sysDepartParamMapper.selectByExample(queryDept);
                if (!ObjectUtils.isEmpty(sysDepartParamDeptList)) {
                    sysDepartParamList = sysDepartParamDeptList;
                    isConfigDept = Constant.STRING_1;
                }
            }
        }else{
            throw new BusinessException("未匹配到单位参数配置记录");
        }

        SysDepartParam sysDepartParam = sysDepartParamList.get(Constant.INTEGER_0);
        //对机构编码、统一信用代码重新赋值
        orgCode = sysDepartParam.getOrgCode();
        uniscid = sysDepartParam.getUnicode();
        if (ObjectUtils.isEmpty(orgCode)) {
            throw new BusinessException("机构记录中未配置机构编码");
        }
        if (ObjectUtils.isEmpty(uniscid)) {
            throw new BusinessException("机构记录中未配置统一社会信用代码");
        }
        ConfigDeptParamVo vo = new ConfigDeptParamVo();
        BeanUtils.copyProperties(sysDepartParam, vo);
        vo.setIsConfigDept(isConfigDept);

        //获取条线信息
        String lineConfig = sysDepartParam.getLineConfig();
        //将条线配置组装成集合对象
        List<LineCaseHandleInfoVo> lineCaseHandleInfo = assembleLineConfigToList(lineConfig);
        vo.setLineCaseHandleInfo(lineCaseHandleInfo);

        //获取印章信息
        ConfigOrgRelatedSealVo sealInfo = configOrgRelatedSealService.getOrgRelatedSealConfigInfo(uniscid,deptCode);
        //getOrgRelatedSealConfigInfo(xx)已经限定了sealInfo不可能为空
        if (ObjectUtils.isEmpty(sealInfo.getId())) {
            log.info("未匹配到印章信息 uniscid:{}", uniscid);
        }
        String sealCode = sealInfo.getSealCode();
        if (ObjectUtils.isEmpty(sealCode)) {
            log.warn("无印章编码 uniscid:" + uniscid);
        }
        vo.setSealCode(sealCode);
        //获取缴款信息
        ConfigPaymentChannelInfoVo paymentInfo = configPaymentChannelInfoService.getPaymentChannelConfigInfoByOrgCode(orgCode,deptCode);
        //getPaymentChannelConfigInfoByOrgCode(xx)已经限定了paymentInfo不可能为空
        String enterCode = paymentInfo.getEnterCode();
        String defaultChitCode = paymentInfo.getDefaultChitCode();
        vo.setEnterCode(enterCode);
        vo.setDefaultChitCode(defaultChitCode);
        vo.setRegiCode(paymentInfo.getRegiCode());
        vo.setRegiName(paymentInfo.getRegiName());
        vo.setDefaultChitName(paymentInfo.getDefaultChitName());
        vo.setEnterName(paymentInfo.getEnterName());
        if (ObjectUtils.isEmpty(enterCode)) {
            log.warn("无执收单位编码 orgCode:" + orgCode);
        }

        if (ObjectUtils.isEmpty(defaultChitCode)) {
            log.warn("无罚没收入编码 orgCode:" + orgCode);
        }

        //新增判定依据配置
        //1.集体议案
        ConfigOrgDecideBasisInfoQueryDto queryDto = new ConfigOrgDecideBasisInfoQueryDto();
        queryDto.setOrgCode(orgCode);
        queryDto.setDecideBasisType(DecideBasisTypeEnum.COLLECTIVE_DISCUSS.getCode());
        ConfigOrgDecideBasisInfo collectiveDiscussConfig = configOrgDecideBasisInfoService.getOrgDecideBasisInfo(queryDto);
        if (!ObjectUtils.isEmpty(collectiveDiscussConfig)) {
            vo.setCollectiveDiscussConfig(collectiveDiscussConfig);
        }

        //2.听证
        queryDto.setDecideBasisType(DecideBasisTypeEnum.HEARING.getCode());
        ConfigOrgDecideBasisInfo hearingConfig = configOrgDecideBasisInfoService.getOrgDecideBasisInfo(queryDto);
        if (!ObjectUtils.isEmpty(hearingConfig)) {
            vo.setHearingConfig(hearingConfig);
        }

        return vo;
    }

    /**
     * 【V2.0.0】描述：保存部门基本参数配置信息
     *
     * @param saveDto {@link ConfigDeptParamDto}
     * @return {@link Result <String>} 保存结果
     * @author xiangyuyu
     * @date 2022-05-16 16:16
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Result<String> saveDeptBasicConfigInfo(ConfigDeptParamDto saveDto) {
        log.info("saveDeptBasicConfigInfo start ... saveDto:{}", saveDto);
        UserDTO userInfo = UserUtil.getUserInfo();
        //String operateType = saveDto.getOperateType();
        String recordSaveType=Constant.STRING_1;
        Example query = new Example(SysDepartParam.class);
        Example.Criteria criteria = query.createCriteria();
        if(StringUtils.isNotBlank(saveDto.getDeptCode())){
            criteria.andEqualTo("orgCode", saveDto.getOrgCode()).andEqualTo("isDeleted",Constant.STRING_0).andEqualTo("deptCode",saveDto.getDeptCode());
            List<SysDepartParam> sysDepartParamDeptList = sysDepartParamMapper.selectByExample(query);
            if (!ObjectUtils.isEmpty(sysDepartParamDeptList)) {
                recordSaveType=Constant.STRING_2;
                saveDto.setId(sysDepartParamDeptList.get(0).getId());
            }else{
                recordSaveType=Constant.STRING_1;
                saveDto.setId(null);
            }
        }else{
            //获取机构基本信息
            if (!ObjectUtils.isEmpty(saveDto.getOrgCode())) {
                criteria.andEqualTo("orgCode", saveDto.getOrgCode());
            }
            criteria.andCondition("(dept_code is null or dept_code='') ").andEqualTo("isDeleted",Constant.STRING_0);
            List<SysDepartParam> sysDepartParamOrgList = sysDepartParamMapper.selectByExample(query);
            if (!ObjectUtils.isEmpty(sysDepartParamOrgList)) {
                recordSaveType=Constant.STRING_2;
                saveDto.setId(sysDepartParamOrgList.get(0).getId());
            }else{
                recordSaveType=Constant.STRING_1;
                saveDto.setId(null);
            }
        }
        if (!RecordSaveTypeEnum.isLegalEnumCode(recordSaveType)) {
            throw new BusinessException("请指定有效的操作类型(1-新增/2-修改)");
        }
        SysDepartParam configDeptConfigInfo = new SysDepartParam();
        if (!ObjectUtils.isEmpty(saveDto)) {
            BeanUtils.copyProperties(saveDto, configDeptConfigInfo);
        }
        //String recordSaveType = saveDto.getOperateType();
        String id;
        //条线配置数据校验
        List<LineCaseHandleInfoVo> lineCaseHandleInfo = saveDto.getLineCaseHandleInfo();

        String errorMsg = validateIsLegalLineConfig(lineCaseHandleInfo,saveDto.getId());
        if (!ObjectUtils.isEmpty(errorMsg)) {
            throw new BusinessException("条线配置错误：" + errorMsg);
        } else {
            //处理成json字符串
            if (!ObjectUtils.isEmpty(lineCaseHandleInfo)) {
                JSON json = (JSON) JSONObject.toJSON(lineCaseHandleInfo);
                String lineConfig = json.toJSONString();
                configDeptConfigInfo.setLineConfig(lineConfig);
            }
        }
        //设置修改人id
        configDeptConfigInfo.setUpdateUserId(userInfo.getUserId().toString());
        configDeptConfigInfo.setUpdateTime(LocalDateTime.now());
        try {
            if (RecordSaveTypeEnum.MOD.getCode().equals(recordSaveType)) {
                id = saveDto.getId();
                if (ObjectUtils.isEmpty(id)) {
                    return Result.error(Constant.STRING_NO_PRIMARY_KEY);
                } else {
                    ConfigDeptParamRequest request = new ConfigDeptParamRequest();
                    request.setUniscid(saveDto.getUnicode());
                    request.setOrgCode(saveDto.getOrgCode());
                    request.setDeptCode(saveDto.getDeptCode());
                    request.setId(saveDto.getId());
                   /* ConfigDeptParamVo vo = getDeptConfigInfoWithSpecialCondition(request);
                    if (ObjectUtils.isEmpty(vo)) {
                        return Result.error("未匹配到机构信息");
                    }*/
                    Example updateE = new Example(SysDepartParam.class);
                    updateE.createCriteria().andEqualTo("id", id);
                    sysDepartParamMapper.updateByExampleSelective(configDeptConfigInfo, updateE);
                }
            } else {

                String uniscid = saveDto.getUnicode();
                if(ObjectUtils.isEmpty(uniscid)){
                    return Result.error("未指定统一社会信用代码");
                }
                id = BaseUtil.createUid();
                configDeptConfigInfo.setId(id);
                if(StringUtils.isNotBlank(saveDto.getDeptCode())){
                    configDeptConfigInfo.setIsConfigDept(Constant.STRING_1);
                    configDeptConfigInfo.setIsDeleted(Constant.STRING_0);
                    //更新不为空的一级部门
                    Example orgExample=new Example(SysDepartParam.class);
                    orgExample.createCriteria().andEqualTo("orgCode",saveDto.getOrgCode()).andEqualTo("isDeleted",Constant.STRING_0).andCondition("(dept_code is null or dept_code='') ");
                    List<SysDepartParam> sysDepartParamOrgs=sysDepartParamMapper.selectByExample(orgExample);
                    if(!ObjectUtils.isEmpty(sysDepartParamOrgs)){
                        for (SysDepartParam sysDepartParam:sysDepartParamOrgs) {
                            SysDepartParam updateSysDepartParam=new SysDepartParam();
                            updateSysDepartParam.setId(sysDepartParam.getId());
                            updateSysDepartParam.setIsConfigDept(Constant.STRING_1);
                            sysDepartParamMapper.updateByPrimaryKeySelective(updateSysDepartParam);
                        }

                    }
                }
                sysDepartParamMapper.insertSelective(configDeptConfigInfo);

            }
            //向证据库同步更新数据
            DeptInfoSyncDto deptInfoSyncDto=new DeptInfoSyncDto();
            deptInfoSyncDto.setDeptCode(saveDto.getOrgCode());
            deptInfoSyncDto.setUniqueCode(saveDto.getUnicode());
            deptInfoSyncDto.setAddress(saveDto.getAddress());
            dealsSyncDeptInfoToEvidenceShare(deptInfoSyncDto);


        } catch (Exception e) {
            e.printStackTrace();
            if (e.getMessage().contains(Constant.STRING_DUPLICATE_ENTRY) ||
                    e.getMessage().contains(Constant.STRING_DUPLICATE_ENTRY_LOWER)) {
                throw new BusinessException("请勿重复添加");
            } else {
                throw e;
            }
        }
        log.info("saveDeptBasicConfigInfo end");
        return Result.success(Constant.STRING_OPERATE_SUCCESS);
    }

    /**
     * 描述：校验条线配置是否配置合法
     *
     * @param lineCaseHandleInfo {@link List<LineCaseHandleInfoVo>}
     * @return String 错误提示
     * @author xiangyuyu
     * @date 2022-05-20 14:44
     */
    private String validateIsLegalLineConfig(List<LineCaseHandleInfoVo> lineCaseHandleInfo,String id) {
        if (ObjectUtils.isEmpty(lineCaseHandleInfo) || lineCaseHandleInfo.size() == 0) {
            return "请至少选择一个办案条线";
        } else {
            //是否没有条线是勾选状态
            boolean isNoLineCheck = true;
            for (LineCaseHandleInfoVo e : lineCaseHandleInfo) {
                String lineCaseHandleStatusCode = e.getLineCaseHandleStatusCode();
                String lineCode = e.getLineCode();
                if (ObjectUtils.isEmpty(lineCode)) {
                    return "未指定条线编码";
                }
                String lineDocNumber = e.getLineDocNumber();
                String lineName = e.getLineName();
                if (YesOrNoEnum.YES.getCode().equals(lineCaseHandleStatusCode)) {
                    if (isNoLineCheck) {
                        isNoLineCheck = false;
                    }

                    if (ObjectUtils.isEmpty(lineName)) {
                        return "未指定该办案条线的条线名称-" + lineName;
                    }
                    if (ObjectUtils.isEmpty(lineDocNumber)) {
                        return "未指定该办案条线的条线文号-" + e.getLineName();
                    }
                } else if(!YesOrNoEnum.isLegalEnumCode(lineCaseHandleStatusCode)){
                    return "请标记条线办案状态";
                }
                //校验条线文号是否重复
                if(YesOrNoEnum.YES.getCode().equals(lineCaseHandleStatusCode)){
                    String lineNumber="%\"lineDocNumber\":\""+lineDocNumber+"\"%";
                    Example example=new Example(SysDepartParam.class);
                    if (ObjectUtil.isNotEmpty(id)){
                        example.createCriteria().andLike("lineConfig",lineNumber)
                                .andNotEqualTo("id", id);
                    }else {
                        example.createCriteria().andLike("lineConfig",lineNumber);
                    }

                    List<SysDepartParam> sysDepartParams = sysDepartParamMapper.selectByExample(example);
                    if (ObjectUtil.isNotEmpty(sysDepartParams) && sysDepartParams.size()>0){
                        return "【" +lineName+"】条线的文号和"+ sysDepartParams.get(0).getOrgStandardName()+sysDepartParams.get(0).getOrgCode()+"的条线文号相同，会导致生成文书文号重复";
                    }
                }
            }
        }
        return "";
    }

    /**
     * 【V2.0.0】描述：保存部门指定配置信息
     *
     * @param saveDto {@link ConfigDeptSpecialParamDto}
     * @return {@link Result<String>} 保存结果
     * @author xiangyuyu
     * @date 2022-05-16 16:16
     */
    @Override
    public Result<String> saveDeptSpecialConfigInfo(ConfigDeptSpecialParamDto saveDto) {
        log.info("saveDeptSpecialConfigInfo start ... saveDto:{}", saveDto);
        //任务分发
        String adjustDeptInfoType = saveDto.getAdjustDeptInfoType();
        if (!AdjustDeptInfoTypeEnum.isLegalEnumCode(adjustDeptInfoType)) {
            return Result.error("未指定有效的调整的部门参数类型 AdjustDeptInfoTypeEnum");
        }
        String operateType = saveDto.getOperateType();
        if(!RecordSaveTypeEnum.isLegalEnumCode(operateType)){
            return Result.error("请指定有效的操作类型");
        }
        if(RecordSaveTypeEnum.ADD.getCode().equals(operateType)){
            return Result.error("目前仅支持修改");
        }
        String uniscid = saveDto.getUniscid();
        String orgCode = saveDto.getOrgCode();
        String orgName = saveDto.getOrgName();
        String deptCode = saveDto.getDeptCode();

        if (AdjustDeptInfoTypeEnum.SEAL.getCode().equals(adjustDeptInfoType)) {
            String sealCode = saveDto.getSealCode();
            if (ObjectUtils.isEmpty(sealCode)) {
                return Result.error("未指定印章编码");
            }
            ConfigOrgRelatedSeal configOrgRelatedSeal = new ConfigOrgRelatedSeal();
            configOrgRelatedSeal.setSealCode(sealCode);
            configOrgRelatedSeal.setOrgName(orgName);
            Example updateSeal = new Example(ConfigOrgRelatedSeal.class);
            if(!StringUtils.isBlank(deptCode)){
                configOrgRelatedSeal.setDeptCode(deptCode);
                updateSeal.createCriteria().andEqualTo("deptCode", deptCode).andEqualTo("uniscid", uniscid);
            }else{
                updateSeal.createCriteria().andEqualTo("uniscid", uniscid);
            }
            int count = configOrgRelatedSealMapper.updateByExampleSelective(configOrgRelatedSeal, updateSeal);
            //证据库同步更新部门数据
            DeptInfoSyncDto deptInfoSyncDto=new DeptInfoSyncDto();
            deptInfoSyncDto.setDeptCode(orgCode);
            deptInfoSyncDto.setSealCode(sealCode);
            if (count > 0) {
                dealsSyncDeptInfoToEvidenceShare(deptInfoSyncDto);
                return Result.success("印章配置信息更新成功");
            } else if (count == 0) {
                log.info("未找到印章配置记录信息 uniscid:{}",uniscid);
                //无记录，需要新增一条
                String sealUid = BaseUtil.createUid();
                configOrgRelatedSeal.setId(sealUid);
                configOrgRelatedSeal.setOrgCode(orgCode);
                configOrgRelatedSeal.setUniscid(uniscid);
                configOrgRelatedSeal.setDeptCode(deptCode);
                int insertSealInfoCount = configOrgRelatedSealMapper.insertSelective(configOrgRelatedSeal);
                if(insertSealInfoCount == 1){
                    log.info("saveDeptSpecialConfigInfo sealInfo insert success!");
                    dealsSyncDeptInfoToEvidenceShare(deptInfoSyncDto);
                    return Result.success("印章配置信息更新成功-新增");
                } else {
                    return Result.error("印章配置信息更新时出现异常-新增");
                }
            } else {
                return Result.error("更新印章配置信息时出现异常");
            }

        } else if (AdjustDeptInfoTypeEnum.PAYMENT.getCode().equals(adjustDeptInfoType)) {
            UserDTO userDTO = UserUtil.getUserInfo();
            if (ObjectUtils.isEmpty(userDTO)) {
                throw new BusinessException("登录失效");
            }
            String enterCode = saveDto.getEnterCode();
            String defaultChitCode = saveDto.getDefaultChitCode();
            String enterName = saveDto.getEnterName();
            String regiCode = saveDto.getRegiCode();
            String regiName = saveDto.getRegiName();

            if (ObjectUtils.isEmpty(enterCode)) {
                return Result.error("未指定执收单位编码");
            }
            if (ObjectUtils.isEmpty(defaultChitCode)) {
                return Result.error("未指定默认执收项目编码");
            }
            if (ObjectUtils.isEmpty(regiCode)) {
                return Result.error("未指定区域编码");
            }
            Example updatePayment = new Example(ConfigPaymentChannelInfo.class);

            if(StringUtils.isNotBlank(deptCode)){
                updatePayment.createCriteria().andEqualTo("orgCode", orgCode).andEqualTo("deptCode",deptCode);
            }else{
                updatePayment.createCriteria().andEqualTo("orgCode", orgCode);
            }
            ConfigPaymentChannelInfo configPaymentChannelInfo = new ConfigPaymentChannelInfo();
            configPaymentChannelInfo.setEnterCode(enterCode);
            configPaymentChannelInfo.setDefaultChitCode(defaultChitCode);
            configPaymentChannelInfo.setEnterName(enterName);
            configPaymentChannelInfo.setRegiCode(regiCode);
            configPaymentChannelInfo.setRegiName(regiName);
            configPaymentChannelInfo.setDefaultChitName(saveDto.getDefaultChitName());
            configPaymentChannelInfo.setUpdateTime(LocalDateTime.now());
            configPaymentChannelInfo.setUpdateUserId(String.valueOf(userDTO.getUserId()));
            int count = configPaymentChannelInfoMapper.updateByExampleSelective(configPaymentChannelInfo, updatePayment);

            if (count > 0) {
                return Result.success("缴款配置信息更新成功");
            } else if (count == 0) {
                log.info("未找到缴款配置记录信息 orgCode:{}", orgCode);
                //无记录，需要新增一条
                String paymentConfigUid = BaseUtil.createUid();
                configPaymentChannelInfo.setId(paymentConfigUid);
                configPaymentChannelInfo.setEnterCode(enterCode);
                configPaymentChannelInfo.setChannelNo("330000022");
                configPaymentChannelInfo.setChannelName("重庆市统一行政处罚办案系统");
                configPaymentChannelInfo.setOpType("I");
                configPaymentChannelInfo.setOrgCode(orgCode);
                configPaymentChannelInfo.setDefaultChitCode(defaultChitCode);
                configPaymentChannelInfo.setDefaultChitName("罚没收入");
                configPaymentChannelInfo.setEnterName(enterName);
                configPaymentChannelInfo.setDeptCode(deptCode);
                configPaymentChannelInfo.setCreateTime(LocalDateTime.now());
                configPaymentChannelInfo.setCreateUserId(String.valueOf(userDTO.getUserId()));
                configPaymentChannelInfo.setUpdateTime(LocalDateTime.now());
                configPaymentChannelInfo.setUpdateUserId(String.valueOf(userDTO.getUserId()));
                int insertPaymentInfoCount = configPaymentChannelInfoMapper.insertSelective(configPaymentChannelInfo);
                if(insertPaymentInfoCount == 1){
                    log.info("saveDeptSpecialConfigInfo paymentInfo insert success!");
                    return Result.success("缴款配置信息更新成功-新增");
                } else {
                    return Result.error("缴款配置信息更新时出现异常-新增");
                }
            } else {
                return Result.error("更新缴款配置信息时出现异常");
            }

        } else {
            //数据归集
            String isAllowDataReport = saveDto.getIsAllowDataReport();
            if (!YesOrNoEnum.isLegalEnumCode(isAllowDataReport)) {
                return Result.error("未指定是否允许数据上报标识(0-否/1-是)");
            }
            Example updateDataReport = new Example(SysDepartParam.class);
            updateDataReport.createCriteria().andEqualTo("orgCode", orgCode)
                    .andEqualTo("unicode", uniscid);
            SysDepartParam configDeptInfo = new SysDepartParam();
            configDeptInfo.setIsAllowDataReport(isAllowDataReport);
            int count = sysDepartParamMapper.updateByExampleSelective(configDeptInfo, updateDataReport);

            if (count > 0) {
                return Result.success("数据归集配置信息更新成功");
            } else if (count == 0) {
                return Result.error("未找到数据归集配置记录信息 orgCode:" + orgCode + " uniscid:" + uniscid);
            } else {
                return Result.error("更新数据归集配置信息时出现异常");
            }
        }
    }

    /**
     * 描述：将条线配置组装成集合对象
     *
     * @param lineConfig 条线配置（json字符串）
     * @return {@link List<LineCaseHandleInfoVo>} 组装好的条线配置集合
     * @author xiangyuyu
     * @date 2022-05-20 14:21
     */
    @Override
    public List<LineCaseHandleInfoVo> assembleLineConfigToList(String lineConfig) {
        List<LineCaseHandleInfoVo> lineCaseHandleInfoNew = new ArrayList<>();
        if (!ObjectUtils.isEmpty(lineConfig) && lineConfig.startsWith(Constant.STRING_LEFT_PARENTHESE)
                && lineConfig.endsWith(Constant.STRING_RIGHT_PARENTHESE)) {
            JSONArray jsonArray = JSONArray.parseArray(lineConfig);
            if (!ObjectUtils.isEmpty(jsonArray) && jsonArray.size() > 0) {
                //解析
                jsonArray.forEach(e -> {
                    JSONObject jsonoBject = (JSONObject) e;
                    LineCaseHandleInfoVo lineConfigInfo = jsonoBject.toJavaObject(LineCaseHandleInfoVo.class);
                    lineConfigInfo.setLineCaseHandleStatusName(YesOrNoEnum.getValueByCode(lineConfigInfo.getLineCaseHandleStatusCode()));
                    lineCaseHandleInfoNew.add(lineConfigInfo);
                });
            }
        }
        return lineCaseHandleInfoNew;
    }

    /**
     * 【V2.0.0】描述：查询案件联合法制审核相关信息
     *
     * @param caseId 案件id
     * @return {@link CaseApprovalCenterInfoVo} 案件联合法制审核相关信息
     * @author tianrunjia
     * @date 2022-05-24 20:21
     */
    @Override
    public CaseApprovalCenterInfoVo getIsApprovalCenterConfig(String caseId) {
        UserDTO userInfo = UserUtil.getUserInfo();
        if(ObjectUtils.isEmpty(userInfo)){
            throw new BusinessException("登录失效");
        }
        CaseApprovalCenterInfoVo vo = new CaseApprovalCenterInfoVo();
        vo.setIsCaseApprovalCenter(YesOrNoEnum.NO.getCode());
        String orgCode = userInfo.getOrgCode();
        String deptCode=userInfo.getDeptCode();
        if(!ObjectUtils.isEmpty(orgCode)){
            /*Example example = new Example(SysDepartParam.class);
            example.createCriteria().andEqualTo("orgCode",orgCode);
            List<SysDepartParam> sysDepartParamList = sysDepartParamMapper.selectByExample(example);
            if(sysDepartParamList.size()>0){
                vo.setIsCaseApprovalCenter(sysDepartParamList.get(0).getIsApprovalCenterUsing());
            }*/
            SysDepartParam sysDepartParam=getSysDepartParamByOrgCodeAndDeptCode(orgCode,deptCode);
            vo.setIsCaseApprovalCenter(sysDepartParam.getIsApprovalCenterUsing());
        }
        vo.setIsCaseApprovalCenterName(YesOrNoEnum.getValueByCode(vo.getIsCaseApprovalCenter()));
        return vo;


    }

    @Override
    public List<LineTerritoryInfoVo> getLineInfoListByOrgCode(String orgCode) {
        UserDTO userDTO=UserUtil.getUserInfo();
        String deptCode=userDTO.getDeptCode();
        SysDepartParam sysDepartParam = getSysDepartParamByOrgCodeAndDeptCode(orgCode,deptCode);
        String lineConfig = sysDepartParam.getLineConfig();
        List<LineTerritoryInfoVo> lineInfoVoList=new ArrayList<>();
        List<LineCaseHandleInfoVo> lineCaseHandleInfoVos = assembleLineConfigToList(lineConfig);
        if (ObjectUtil.isEmpty(lineConfig)){
            throw new BusinessException("办案机构暂未配置条线信息，请联系管理员");
        }
        if (ObjectUtil.isNotEmpty(lineCaseHandleInfoVos) && lineCaseHandleInfoVos.size()>0){
            for (LineCaseHandleInfoVo lineCaseHandleInfoVo:lineCaseHandleInfoVos){
                //未开启 过滤
                if(Constant.STRING_0.equals(lineCaseHandleInfoVo.getLineCaseHandleStatusCode())){
                    continue;
                }
                LineTerritoryInfoVo lineInfoVo=new LineTerritoryInfoVo();
                lineInfoVo.setLineCaseHandleStatusCode(lineCaseHandleInfoVo.getLineCaseHandleStatusCode());
                lineInfoVo.setLineCaseHandleStatusName(lineCaseHandleInfoVo.getLineCaseHandleStatusName());
                lineInfoVo.setLineCode(lineCaseHandleInfoVo.getLineCode());
                lineInfoVo.setLineName(lineCaseHandleInfoVo.getLineName());
                lineInfoVo.setLineDocNumber(lineCaseHandleInfoVo.getLineDocNumber());
                lineInfoVoList.add(lineInfoVo);
            }
        }
        return lineInfoVoList;
    }

    @Override
    public LineTerritoryInfoVo getLineInfoByOrgCodeAndLineCode(String orgCode,String deptCode, String lineCode) {
        SysDepartParam sysDepartParam = getSysDepartParamByOrgCode(orgCode,deptCode);
        String lineConfig = sysDepartParam.getLineConfig();
        List<LineCaseHandleInfoVo> lineCaseHandleInfoVos = assembleLineConfigToList(lineConfig);
        if (ObjectUtil.isEmpty(lineCaseHandleInfoVos)){
            throw new BusinessException("暂未配置条线信息，请联系管理员");
        }
        lineCaseHandleInfoVos=  lineCaseHandleInfoVos.stream().filter(e->e.getLineCode().equals(lineCode)).collect(Collectors.toList());
        if (ObjectUtil.isEmpty(lineCaseHandleInfoVos)){
            throw new BusinessException("办案机构暂未配置条线信息，请联系管理员");
        }
        lineCaseHandleInfoVos=  lineCaseHandleInfoVos.stream().filter(e->e.getLineCode().equals(lineCode)).collect(Collectors.toList());
       if (lineCaseHandleInfoVos.size()>0){
           LineCaseHandleInfoVo lineCaseHandleInfoVo=lineCaseHandleInfoVos.get(0);
           LineTerritoryInfoVo lineTerritoryInfoVo = new  LineTerritoryInfoVo();
           LineDTO lineDto = xzzfInterfaceService.getLineInfoByLineCode(lineCode);
           lineTerritoryInfoVo.setTerritoryCode(lineDto.getTerritoryCode());
           lineTerritoryInfoVo.setTerritoryName(lineDto.getTerritoryName());
           lineTerritoryInfoVo.setLineCaseHandleStatusCode(lineCaseHandleInfoVo.getLineCaseHandleStatusCode());
           lineTerritoryInfoVo.setLineCaseHandleStatusName(lineCaseHandleInfoVo.getLineCaseHandleStatusName());
           lineTerritoryInfoVo.setLineCode(lineCaseHandleInfoVo.getLineCode());
           lineTerritoryInfoVo.setLineName(lineCaseHandleInfoVo.getLineName());
           lineTerritoryInfoVo.setLineDocNumber(lineCaseHandleInfoVo.getLineDocNumber());
           return lineTerritoryInfoVo;
       }
        return null;
    }

    /**
     * 描述: 根据登录人部门查询条线配置
     *
     * @return java.lang.String
     * @author zhanghongqiang
     * @Date 2022/10/28
     */
    @Override
    public List<String> getDeptLineConfig() {
        List<String> result = new ArrayList<>();
        UserDTO userInfo = UserUtil.getUserInfo();
        String orgCode = userInfo.getOrgCode();
        /*SysDepartParam sysDepartParam = new SysDepartParam();
        sysDepartParam.setOrgCode(orgCode);
        SysDepartParam sysDepartParamSelect = sysDepartParamMapper.selectOne(sysDepartParam);*/
        String deptCode=userInfo.getDeptCode();
        SysDepartParam sysDepartParamSelect=getSysDepartParamByOrgCodeAndDeptCode(orgCode,deptCode);
        String lineConfig = sysDepartParamSelect.getLineConfig();
        if (StringUtils.isNotBlank(lineConfig)) {
            List<Map<String,String>> listObjectFir = (List<Map<String,String>>) JSONArray.parse(lineConfig);
            for (Map<String, String> map : listObjectFir) {
                String lineCaseHandleStatusName = map.get("lineCaseHandleStatusName");
                if (Constant.OPEN.equals(lineCaseHandleStatusName)){
                    String lineCode = map.get("lineCode").substring(0,4);
                    result.add(lineCode);
                }
            }
        }
        return result;
    }
    /**
     * 删除机构配置信息
     * @author liyafeng
     * @date 2022/11/23
      * @param request
     * @return {@link int}
     */
    @Override
    public int invalidSysDepartParam(ConfigDeptParamRequest request) {
        if(StringUtils.isAnyBlank(request.getOrgCode(),request.getDeptCode())){
            throw new BusinessException("部门编码或机构编码不能为空！");
        }
        SysDepartParam sysDepartParam=getSysDepartParamByOrgCodeAndDeptCode(request.getOrgCode(),request.getDeptCode());
        int num=sysDepartParamMapper.updateSysDepartParamInvalid(request.getOrgCode(),request.getDeptCode());
        //删除已配置印章
        configOrgRelatedSealMapper.deleteConfigOrgRelatedSeal(sysDepartParam.getUnicode(),request.getDeptCode());
        //删除已配置支付信息
        configPaymentChannelInfoMapper.deleteConfigPaymentChannelInfo(request.getOrgCode(),request.getDeptCode());
        return num;
    }
    /**
     * 根据部门编码与机构编码获取对应的参数配置
     * @author liyafeng
     * @date 2022/11/23
      * @param orgCode
     * @param deptCode
     * @return {@link SysDepartParam}
     */
    @Override
    public SysDepartParam getSysDepartParamByOrgCodeAndDeptCode(String orgCode,String deptCode) {
        List<SysDepartParam> sysDepartParams=new ArrayList<>();
        SysDepartParam sysDepartParam=new SysDepartParam();
        String isConfigDept=Constant.STRING_0;
        Example example = new Example(SysDepartParam.class);
        example.createCriteria().andEqualTo("orgCode",orgCode).andCondition("(dept_code is null or dept_code='') ").andEqualTo("isDeleted",Constant.STRING_0);
        sysDepartParams = sysDepartParamMapper.selectByExample(example);
        if (!ObjectUtils.isEmpty(sysDepartParams)){
            sysDepartParam = sysDepartParams.get(Constant.INTEGER_0);
            isConfigDept=sysDepartParams.get(Constant.INTEGER_0).getIsConfigDept();
        }
        if(Constant.STRING_1.equals(isConfigDept)&&StringUtils.isNotBlank(deptCode)){
            Example deptExample = new Example(SysDepartParam.class);
            deptExample.createCriteria().andEqualTo("orgCode",orgCode).andEqualTo("deptCode",deptCode).andEqualTo("isDeleted",Constant.STRING_0);
            sysDepartParams = sysDepartParamMapper.selectByExample(deptExample);
            if(!ObjectUtils.isEmpty(sysDepartParams)){
                sysDepartParam=sysDepartParams.get(0);
            }
        }
        return sysDepartParam;
    }
    /**
     * 根据部门编码查询部门信息
     * @author wangfawei
     * @date 2022-12-09
     * @param recordDto
     * @return {@link SysDepartParam}
     */
    @Override
    public Result<SysDepartParam> getSysDepartParam(CaseAdditionalRecordDto recordDto) {
        Example example = new Example(SysDepartParam.class);
        Example.Criteria criteria = example.createCriteria();
        criteria.andEqualTo("orgCode", recordDto.getOrgCode());
        List<SysDepartParam> sysDepartParamList = sysDepartParamMapper.selectByExample(example);
        if(sysDepartParamList.size()>0) {
            return Result.success(Constant.STRING_GET_SUCCESS, sysDepartParamList.get(0));
        }
        return Result.error(Constant.STRING_GET_FAIL);
    }

    @Override
    public LineTerritoryInfoVo getLineInfoByOrgCodeAndLineCodeNumber(String orgCode, String deptCode, String lineCode) {
        SysDepartParam sysDepartParam = getSysDepartParamByOrgCode(orgCode,deptCode);
        String lineConfig = sysDepartParam.getLineConfig();
        List<LineCaseHandleInfoVo> lineCaseHandleInfoVos = assembleLineConfigToList(lineConfig);
        if (ObjectUtil.isEmpty(lineCaseHandleInfoVos)){
            throw new BusinessException("暂未配置条线信息，请联系管理员");
        }
        lineCaseHandleInfoVos=  lineCaseHandleInfoVos.stream().filter(e->e.getLineCode().equals(lineCode)).collect(Collectors.toList());
        if (ObjectUtil.isEmpty(lineCaseHandleInfoVos)){
            throw new BusinessException("办案机构暂未配置条线信息，请联系管理员");
        }
        lineCaseHandleInfoVos=  lineCaseHandleInfoVos.stream().filter(e->e.getLineCode().equals(lineCode)).collect(Collectors.toList());
        if (lineCaseHandleInfoVos.size()>0){
            LineCaseHandleInfoVo lineCaseHandleInfoVo=lineCaseHandleInfoVos.get(0);
            LineTerritoryInfoVo lineTerritoryInfoVo = new  LineTerritoryInfoVo();
            //LineDTO lineDto = xzzfInterfaceService.getLineInfoByLineCode(lineCode);
            //lineTerritoryInfoVo.setTerritoryCode(lineDto.getTerritoryCode());
            //lineTerritoryInfoVo.setTerritoryName(lineDto.getTerritoryName());
            lineTerritoryInfoVo.setLineCaseHandleStatusCode(lineCaseHandleInfoVo.getLineCaseHandleStatusCode());
            lineTerritoryInfoVo.setLineCaseHandleStatusName(lineCaseHandleInfoVo.getLineCaseHandleStatusName());
            lineTerritoryInfoVo.setLineCode(lineCaseHandleInfoVo.getLineCode());
            lineTerritoryInfoVo.setLineName(lineCaseHandleInfoVo.getLineName());
            lineTerritoryInfoVo.setLineDocNumber(lineCaseHandleInfoVo.getLineDocNumber());
            return lineTerritoryInfoVo;
        }
        return null;
    }

    private void dealsSyncDeptInfoToEvidenceShare(DeptInfoSyncDto deptInfoSyncDto){
        Map<String, Object> map = evidenceInventoryService.syncDeptInfoToEvidenceShare(deptInfoSyncDto);
        Integer code = (Integer) map.get("code");
        if (code!=Result.DEFAULT_SUCCESS){
            log.info("同步部门信息到证据库失败");
        }
    }

    public static void main(String[] args) {
        //获取条线信息
        List<LineCaseHandleInfoVo> lineCaseHandleInfo = new ArrayList<>();
        LineCaseHandleInfoVo vo = new LineCaseHandleInfoVo();
        vo.setLineCode("1");
        vo.setLineName("建设");
        vo.setLineCaseHandleStatusCode("1");
        vo.setLineDocNumber("xx建设");
        lineCaseHandleInfo.add(vo);
        vo = new LineCaseHandleInfoVo();
        vo.setLineCode("838");
        vo.setLineName("城市");
        vo.setLineCaseHandleStatusCode("0");
        vo.setLineDocNumber("城市001");
        lineCaseHandleInfo.add(vo);

        JSON json = (JSON)JSONObject.toJSON(lineCaseHandleInfo);

        String lineConfig = json.toJSONString();

        List<LineCaseHandleInfoVo> lineCaseHandleInfoNew = new ArrayList<>();
        if(!ObjectUtils.isEmpty(lineConfig) && lineConfig.startsWith("[") && lineConfig.endsWith("]")){
            JSONArray jsonArray = JSONArray.parseArray(lineConfig);
            if(!ObjectUtils.isEmpty(jsonArray) && jsonArray.size() > 0){
                //解析
                jsonArray.forEach(e->{
                    JSONObject jsonoBject = (JSONObject)e;
                    LineCaseHandleInfoVo lineConfigInfo = jsonoBject.toJavaObject(LineCaseHandleInfoVo.class);
                    System.out.println(lineConfigInfo);
                    lineCaseHandleInfoNew.add(lineConfigInfo);
                });
            }

        }
        System.out.println(lineCaseHandleInfoNew);
    }

    /**
     * 描述：根据org查询国标区划编码
     *
     * @param orgCode 机构编码
     * @return 国标区划编码
     * @author xiangyuyu
     * @date 2022/11/30
     * @since
     */
    @Override
    public String getGbOrgInfo(String orgCode) {
        return sysDepartParamMapper.selectGbOrgInfo(orgCode);
    }
}
